"""
V3 
多线程
同时执行左右摇杆命令
固定命令行
"""
import pygame
import vgamepad as vg
import time
import threading
import keyboard

# 命令映射
command_map = {
    'w': ('left', 0.0, 1.0, "左摇杆向上移动"),
    's': ('left', 0.0, -1.0, "左摇杆向下移动"),
    'a': ('left', -1.0, 0.0, "左摇杆向左移动"),
    'd': ('left', 1.0, 0.0, "左摇杆向右移动"),
    '上': ('right', 0.0, 1.0, "右摇杆向上移动"),
    '下': ('right', 0.0, -1.0, "右摇杆向下移动"),
    '左': ('right', -1.0, 0.0, "右摇杆向左移动"),
    '右': ('right', 1.0, 0.0, "右摇杆向右移动"),
    'A': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_A, "A按钮"),
    'B': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_B, "B按钮"),
    'X': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_X, "X按钮"),
    'Y': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_Y, "Y按钮"),
    '空': ('empty')
}

class GamepadController:
    def __init__(self):
        self.gamepad = vg.VX360Gamepad()
        self.running = True
        self.paused = False
        self.left_thread = None
        self.right_thread = None
        self.button_thread = None
        print("虚拟手柄创建成功")
    
    def pause(self):
        """暂停执行"""
        self.paused = True
        print("执行已暂停")
    
    def resume(self):
        """恢复执行"""
        self.paused = False
        print("执行已恢复")
    
    def stop(self):
        """停止执行"""
        self.running = False
        print("执行已停止")
        
        # 重置所有摇杆和按钮
        self.gamepad.left_joystick_float(x_value_float=0.0, y_value_float=0.0)
        self.gamepad.right_joystick_float(x_value_float=0.0, y_value_float=0.0)
        self.gamepad.update()
    
    def execute_left_commands(self, command_string):
        """执行左摇杆命令（独立线程）"""
        for char in command_string:
            if not self.running:
                break
                
            while self.paused:
                time.sleep(0.3)
                if not self.running:
                    return
                    
            if char in command_map and command_map[char][0] == 'left':
                command = command_map[char]
                _, x_axis, y_axis, _ = command
                
                # 设置左摇杆位置
                self.gamepad.left_joystick_float(x_value_float=x_axis, y_value_float=y_axis)
                self.gamepad.update()
                print(f"左摇杆移动到: X={x_axis}, Y={y_axis}")
                
                time.sleep(1)  # 保持位置一段时间
                
                # 重置左摇杆
                self.gamepad.left_joystick_float(x_value_float=0.0, y_value_float=0.0)
                self.gamepad.update()
                print("左摇杆回中")
            
            elif char in command_map and command_map[char][0] == 'button':
                command = command_map[char]
                _, button, _ = command
                
                self.gamepad.press_button(button=button)
                self.gamepad.update()
                print(f"按下按钮: {button}")
                
                time.sleep(1)  # 短暂按下
                
                # 释放按钮
                self.gamepad.release_button(button=button)
                self.gamepad.update()
                print(f"释放按钮: {button}")
                
            # time.sleep(0.1)  # 命令间间隔
    
    def execute_right_commands(self, command_string):
        """执行右摇杆命令（独立线程）"""
        for char in command_string:
            if not self.running:
                break
                
            while self.paused:
                time.sleep(0.3)
                if not self.running:
                    return
                    
            if char in command_map and command_map[char][0] == 'right':
                command = command_map[char]
                _, x_axis, y_axis, _ = command
                
                # 设置右摇杆位置（与左摇杆同时！）
                self.gamepad.right_joystick_float(x_value_float=x_axis, y_value_float=y_axis)
                self.gamepad.update()
                print(f"右摇杆移动到: X={x_axis}, Y={y_axis}")
                
                time.sleep(1)  # 保持位置一段时间
                
                # 重置右摇杆
                self.gamepad.right_joystick_float(x_value_float=0.0, y_value_float=0.0)
                self.gamepad.update()
                print("右摇杆回中")
                
            # time.sleep(0.1)  # 命令间间隔
    
    def execute_concurrent_sequence(self, left_commands, right_commands):
        """同时执行所有命令"""
        
        print(f"左摇杆命令: {left_commands}")
        print(f"右摇杆命令: {right_commands}")
        
        # 创建并启动两个独立线程
        self.left_thread = threading.Thread(target=self.execute_left_commands, args=(left_commands,))
        self.right_thread = threading.Thread(target=self.execute_right_commands, args=(right_commands,))
        
        self.left_thread.daemon = True
        self.right_thread.daemon = True
        
        self.left_thread.start()
        self.right_thread.start()
        
        # 等待所有线程完成
        self.left_thread.join()
        self.right_thread.join()
        
        # 清理
        self.gamepad.reset()
        self.gamepad.update()
        print("命令序列执行完成")


if __name__ == "__main__":
    controller = GamepadController()
    time.sleep(5)
    
    # 示例：同时控制左右摇杆
    left_commands = "wswsAwwssad"  # 左摇杆、右摇杆、按钮同时操作
    right_commands = "左左左左左左左左左左左左左左左"  # 左摇杆、右摇杆、按钮同时操作
    
    # 启动执行
    controller.execute_concurrent_sequence(left_commands, right_commands)
    
    # 添加键盘监听用于暂停/恢复/停止
    keyboard.add_hotkey('p', controller.pause)
    keyboard.add_hotkey('r', controller.resume)
    keyboard.add_hotkey('s', controller.stop)
    
    print("按 P 暂停，按 R 恢复，按 S 停止")
    
    # 保持程序运行
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        controller.stop()
        print("程序退出")